﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Cost.Models;
using NBlock.MVCControl;

namespace Cost.Controllers
{
    public class StorageManageController : Controller
    {
         #region 构造函数
         private readonly ICostRepository<Storage> storageRepository;
         private readonly ICostRepository<StorageRecord> storagerecordRepository;

         public StorageManageController(ICostRepository<Storage> storageRepository, ICostRepository<StorageRecord> storagerecordRepository)
        {
            this.storageRepository = storageRepository;
            this.storagerecordRepository = storagerecordRepository;
        }
        #endregion

        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public JsonResult List(nbPageInfo pager, nbSearchCondition where)
        {
            var pageData = storageRepository.GetPageable(pager, where);
            var data = pager.ToGridData(pageData);
            return Json(data);
        }

        public ActionResult Edit(string Id)
        {
            var data = storageRepository.Find(Id) ?? new Storage();
            return View(data);
        }

        [HttpPost]
        public JsonResult Save(string Id)
        {
            var data = storageRepository.Find(Id) ?? new Storage();
            //保存历史记录
            if (storagerecordRepository.Find(s => s.StorageId == data.Id) == null)
            {
                //保存变更记录
                var item = new StorageRecord()
                {
                    StorageId = data.Id,
                    MaterialId = data.MaterialId,
                    Code = data.Code,
                    Name = data.Name,
                    Unit = data.Unit,
                    Specification = data.Specification,
                    CurrentPrice = data.CurrentPrice,
                    ActualSorage = data.ActualStorage,
                    Type = data.Type,
                    Category = data.Category
                };
                storagerecordRepository.Insert(item);
            }

            TryUpdateModel(data);
            storageRepository.Save(data);
            //保存变更记录
            var record = new StorageRecord()
            {
                StorageId = data.Id,
                MaterialId = data.MaterialId,
                Code = data.Code,
                Name = data.Name,
                Unit = data.Unit,
                Specification = data.Specification,
                CurrentPrice = data.CurrentPrice,
                ActualSorage = data.ActualStorage,
                Type = data.Type,
                Category = data.Category
            };
            storagerecordRepository.Insert(record);

            return Json(AjaxMessage.Successful);
        }
    }
}
